from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.exc import IntegrityError, OperationalError
from jose import JWTError
import logging

from app.api.v1.api import api_router
from app.core.exceptions import (
    database_exception_handler,
    integrity_exception_handler,
    jwt_exception_handler,
    http_exception_handler,
    general_exception_handler
)
from app.core.service_init import initialize_all_services, get_service_status
from app.services.celery_worker_manager import celery_worker_manager

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)

app = FastAPI(
    title="ThrushAI Backend",
    description="Backend services for the ThrushAI project - AI创作社交平台",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# CORS中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境中应该配置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 异常处理器
app.add_exception_handler(OperationalError, database_exception_handler)
app.add_exception_handler(IntegrityError, integrity_exception_handler)
app.add_exception_handler(JWTError, jwt_exception_handler)
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(Exception, general_exception_handler)

# 包含API路由
app.include_router(api_router, prefix="/api")

# 初始化所有第三方服务
@app.on_event("startup")
async def startup_event():
    """应用启动时初始化所有服务"""
    logger = logging.getLogger(__name__)
    try:
        # 初始化AI服务
        initialize_all_services()
        logger.info("所有AI服务初始化完成")
        
        # 自动启动Celery Worker - 监听所有即梦AI队列
        worker_started = celery_worker_manager.start_worker(
            app_name="app.celery_app",
            queues="jimeng_video,jimeng_image,jimeng_template", 
            concurrency=1,
            loglevel="info"
        )
        
        if worker_started:
            logger.info("Celery Worker自动启动成功")
        else:
            logger.warning("Celery Worker自动启动失败，队列功能可能不可用")
        
    except Exception as e:
        logger.error(f"服务初始化失败: {e}")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时清理资源"""
    logger = logging.getLogger(__name__)
    try:
        # 停止Celery Worker
        celery_worker_manager.stop_worker()
        logger.info("Celery Worker已停止")
    except Exception as e:
        logger.error(f"服务清理失败: {e}")

@app.get("/")
def read_root():
    """API根端点 - 返回欢迎信息"""
    return {
        "message": "Welcome to ThrushAI API",
        "version": "1.0.0",
        "docs": "/docs",
        "status": "running"
    }

@app.get("/health")
def health_check():
    """健康检查端点"""
    return {"status": "healthy", "service": "thrush-ai-backend"}

@app.get("/api/status")
def service_status():
    """服务状态检查端点"""
    return get_service_status()

@app.get("/api/worker/status")  
def worker_status():
    """Celery Worker状态检查端点"""
    return celery_worker_manager.get_status()

